
import os,json,re
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AnsibleGUI.settings')
django.setup()

from django.core import serializers as se
from webapp.models import *
from webapp.serializer import *

def nginx_http_template():
   nginx_http_template = {}
   nginx_list = NginxTemplate.objects.all()
   for nginx in nginx_list:
      website_query = NginxSerializer(nginx)
      nginx_http_template[website_query.data['template_name']] = website_query.data
      nginx_http_template[website_query.data['template_name']]["reverse_proxy"] = {}
      nginx_http_template[website_query.data['template_name']]["reverse_proxy"]["locations"] = {}
      upstream_dict = {}
      host_dict = {}
      nginx_http_template[website_query.data['template_name']]["upstreams"] = upstream_dict
      locations = nginx.templates.all()
      for u in locations:
         if u.proxy_type is True:
            nginx_http_template[website_query.data['template_name']]["reverse_proxy"]["locations"][u.name] = {}
            nginx_http_template[website_query.data['template_name']]["reverse_proxy"]["locations"][u.name][
               'location'] = u.location
            nginx_http_template[website_query.data['template_name']]["reverse_proxy"]["locations"][u.name][
               "proxy_pass"] = 'http://' + u.locations.all()[0].name
            for upstream in u.locations.all():
               upstream_dict[(UpstreamDetailSerializer(upstream).data)['name']] = UpstreamDetailSerializer(upstream).data
               upstream_dict[(UpstreamDetailSerializer(upstream).data)['name']]['servers'] = host_dict
               for host in upstream.servers.all():
                  host_dict[host.hostname] = HostSerializer(host).data
   str_json = json.dumps(nginx_http_template)
   return (str_json)

if __name__ == '__main__':
   print(nginx_http_template())

